import React , { useEffect,useState,useRef,useCallback  }from 'react';
import { Card, Button, Form, Input, Select, Space, Table, Col, Row, InputNumber } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import SystemDictSelect from '@/pages/Financial/Payment/components/SystemDictSelect';
import {  ProFormSelect, } from '@ant-design/pro-components';
import { get_map } from '@/services/system_api';
import { FormattedMessage, useIntl, useModel } from "@umijs/max";

const { Option } = Select;

interface PackageInfoProps {
    form: any;
    formData: any;
    setFormData: (data: any) => void;
}

const PackageInfo: React.FC<PackageInfoProps> = ({ form, formData, setFormData }) => {
    const [internalForm] = Form.useForm();
    const [initBoxUnits, setInitBoxUnits] = useState<any>([]);
    const intl = useIntl();
    useEffect(() => {
          const fetchFeeOptions = async () => {
             await initBoxUnitsFunc();  
          };
          fetchFeeOptions();
    }, []); 

    const initBoxUnitsFunc = async () => {
          try {
            const response = await get_map("elm_box_type");
            if (response.code != 0) {
              if (!response.msg) {
                throw new Error(intl.formatMessage({ id: "request.error.create" }));
              } else {
                message.error(response.msg);
              }
            }
            setInitBoxUnits(response.data)
            // return response.data;
          } finally {
            // setLoading(false);
          }
        };
    useEffect(() => {
        if (form) {
            // console.log(formData);
            form.internalForms = form.internalForms || [];
            form.internalForms.push(internalForm);
        }
    }, [form]);
    const handleAddPackage = () => {
        setFormData(prev => ({
            ...prev,
            boxs: [
                ...prev.boxs,
                {
                    boxUnit: '',
                    boxQuantity: '',
                    boxLength: '',
                    boxWidth: '',
                    boxHeight: '',
                    boxWeight: '',
                    boxWeightUnit: 'lbs',
                    boxLengthUnit: 'inches',
                    boxDescription: ''
                }
            ]
        }));
    };

    const handleRemovePackage = (index: number) => {
        const newPackages = [...formData.boxs];
        newPackages.splice(index, 1);
        setFormData(prev => ({
            ...prev,
            boxs: newPackages
        }));
    };

    const handlePackageChange = (index: number, field: string, value: any) => {
        const newPackages = [...formData.boxs];
        newPackages[index][field] = value;
        setFormData(prev => ({
            ...prev,
            boxs: newPackages
        }));
    };

   return (
     <Card
       title={intl.formatMessage({ id: "pages.order.packageInfo.title" })}
       size="small"
       extra={
         <Button
           type="primary"
           icon={<PlusOutlined />}
           onClick={handleAddPackage}
         >
           {intl.formatMessage({ id: "pages.order.packageInfo.addPackage" })}
         </Button>
       }
     >
       <Form layout="vertical" initialValues={formData}>
         {formData.boxs.map((pkg: any, index: number) => (
           <Card
             key={index}
             type="inner"
             size="small"
             title={intl.formatMessage(
               { id: "pages.order.packageInfo.packageTitle" },
               { number: index + 1 }
             )}
             style={{ marginBottom: "10px", paddingBottom: "10px" }}
             extra={
               formData.boxs.length > 1 && (
                 <Button
                   danger
                   icon={<DeleteOutlined />}
                   onClick={() => handleRemovePackage(index)}
                 />
               )
             }
           >
             <Row gutter={[16, 16]}>
               <Col xs={24} md={8} xxl={4}>
                 <Form.Item
                   name={[index, "boxUnit"]}
                   label={intl.formatMessage({
                     id: "pages.order.packageInfo.packageType",
                   })}
                   rules={[
                     {
                       required: true,
                       message: intl.formatMessage({
                         id: "validation.package.type.required",
                       }),
                     },
                   ]}
                   initialValue={pkg?.boxUnit}                  
                 >
                  <Select                     
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.selectPlaceholder",
                     })}
                     style={{ width: "100%" }}
                     options={initBoxUnits}   
                     value={pkg?.boxUnit}   
                     onChange={(e) =>
                       handlePackageChange(index, "boxUnit", e)
                     } 
                   />
                   {/* <ProFormSelect
                     name={[index, "boxUnit"]}
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.selectPlaceholder",
                     })}
                     options={initBoxUnits}       
                     fieldProps={{                                          
                       onChange: (value) =>
                         handlePackageChange(index, "boxUnit", value),
                     }}
                   /> */}
                 </Form.Item>
               </Col>
               <Col xs={24} md={8} xxl={4}>
                 <Form.Item
                   name={[index, "boxQuantity"]}
                   label={intl.formatMessage({
                     id: "pages.order.packageInfo.quantity",
                   })}
                   required
                   initialValue={pkg?.boxQuantity}
                 >
                   <InputNumber
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.quantity",
                     })}
                     style={{ width: "100%" }}
                     value={pkg?.boxQuantity}
                     onChange={(e) =>
                       handlePackageChange(index, "boxQuantity", e)
                     }
                   />
                 </Form.Item>
               </Col>

               <Col xs={24} md={8} xxl={4}>
                 <Form.Item
                   name={[index, "boxWeight"]}
                   label={intl.formatMessage({
                     id: "pages.order.packageInfo.weight",
                   })}
                   required
                   initialValue={pkg?.boxWeight}
                 >
                   <InputNumber
                     style={{ width: "calc(100%)" }}
                     value={pkg?.boxWeight}
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.weight",
                     })}
                     onChange={(e) =>
                       handlePackageChange(index, "boxWeight", e)
                     }
                   />
                 </Form.Item>
               </Col>

               <Col xs={24} md={8} xxl={4}>
                 <Form.Item
                   name={[index, "boxLength"]}
                   label={intl.formatMessage({
                     id: "pages.order.packageInfo.length",
                   })}
                   required
                   initialValue={pkg?.boxLength}
                 >
                   <InputNumber
                     style={{ width: "calc(100%)" }}
                     value={pkg?.boxLength}
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.length",
                     })}
                     onChange={(e) =>
                       handlePackageChange(index, "boxLength", e)
                     }
                   />
                 </Form.Item>
               </Col>

               <Col xs={24} md={8} xxl={4}>
                 <Form.Item
                   name={[index, "boxWidth"]}
                   label={intl.formatMessage({
                     id: "pages.order.packageInfo.width",
                   })}
                   required
                   initialValue={pkg?.boxWidth}
                 >
                   <InputNumber
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.width",
                     })}
                     style={{ width: "100%" }}
                     value={pkg?.boxWidth}
                     onChange={(e) => handlePackageChange(index, "boxWidth", e)}
                   />
                 </Form.Item>
               </Col>

               <Col xs={24} md={8} xxl={4}>
                 <Form.Item
                   name={[index, "boxHeight"]}
                   label={intl.formatMessage({
                     id: "pages.order.packageInfo.height",
                   })}
                   required
                   initialValue={pkg?.boxHeight}
                 >
                   <InputNumber
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.height",
                     })}
                     style={{ width: "100%" }}
                     value={pkg?.boxHeight}
                     onChange={(e) =>
                       handlePackageChange(index, "boxHeight", e)
                     }
                   />
                 </Form.Item>
               </Col>
             </Row>
             <Row gutter={[16, 16]}>
               <Col span={24} style={{ marginTop: 12 }}>
                 <Form.Item
                   name={[index, "boxDescription"]}
                   label={intl.formatMessage({
                     id: "pages.order.packageInfo.description",
                   })}
                   initialValue={pkg?.boxDescription}
                   required
                 >
                   <Input
                     placeholder={intl.formatMessage({
                       id: "pages.order.packageInfo.description",
                     })}
                     style={{ width: "100%" }}
                     value={pkg?.boxDescription}
                     onChange={(e) =>
                       handlePackageChange(
                         index,
                         "boxDescription",
                         e.target.value
                       )
                     }
                   />
                 </Form.Item>
               </Col>
             </Row>
           </Card>
         ))}
       </Form>
     </Card>
   );
};

export default PackageInfo;